package com.sgb.kjwl.viewmodel.packers;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.reflect.TypeToken;

import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.EmploymentEntity;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.kjwl.model.entity.TenderListEntity;
import com.sgb.kjwl.model.entity.packers.LabourServiceAndEmploymentEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.MenuEntity;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FigureCheckViewModel extends BaseViewModel {

    public MutableLiveData<LatLng> ldLatLng = new MutableLiveData<>();

    public MutableLiveData<RegeocodeAddress> ldAddress=new MutableLiveData<>();

    public MutableLiveData<Map<String,Object>> ldGetData=new MutableLiveData<>();

    public MutableLiveData<List<EmploymentEntity>> ldEmployment=new MutableLiveData<>();

    public MutableLiveData<List<LabourServiceAndEmploymentEntity>> ldLabour=new MutableLiveData<>();

    public MutableLiveData<List<TenderListEntity>> ldTender=new MutableLiveData<>();

    public MutableLiveData<Boolean> ldDelEmployment=new MutableLiveData<>();

    public MutableLiveData<Boolean> ldDelLabour=new MutableLiveData<>();

    public MutableLiveData<Boolean> ldFollow=new MutableLiveData<>();

    public MutableLiveData<Boolean> mSignUpSuccessLiveData = new MutableLiveData<>();
    // 一级联动数据
    private final List<AddressEntity> mProvinceList = new ArrayList<>();
    // 二级联动数据
    private final List<List<AddressEntity>> mCityList = new ArrayList<>();
    // 三级联动数据
    private final List<List<List<AddressEntity>>> mDistrictList = new ArrayList<>();
    public MutableLiveData<String> mImLiveData = new MutableLiveData<>();
    public MutableLiveData<String > mImbLiveData = new MutableLiveData<>();
    public MutableLiveData<Boolean > mSuccessGetData = new MutableLiveData<>();
    public MutableLiveData<Boolean > mFailGetData = new MutableLiveData<>();
    public MutableLiveData<Boolean > mLoadGetData = new MutableLiveData<>();
    public MutableLiveData<List<EmploymentEntity>> getEmploymentList=new MutableLiveData<>();
    public MutableLiveData<List<LabourServiceAndEmploymentEntity>> getLabourList=new MutableLiveData<>();
    public MutableLiveData<List<TenderListEntity>> getTenderList=new MutableLiveData<>();
    public MutableLiveData<List<AddressEntity>> mSuccessWorkType = new MutableLiveData<>();
    public MutableLiveData<Integer> mFocus=new MutableLiveData<>();
    public MutableLiveData<String> mUrlTenderLiveData = new MutableLiveData<>();

    public FigureCheckViewModel(@NonNull @NotNull Application application) {
        super(application);
    }
    /**
     * 个人工队发布数据
     * @return
     */
    public List<MenuEntity> getPersonTeamList() {
        List<MenuEntity> list = new ArrayList<>();
        list.add(new MenuEntity("工人发布",""+ R.drawable.icon_workers,R.drawable.icon_workers));
        list.add(new MenuEntity("用工发布",""+ R.drawable.icon_team_employment,R.drawable.icon_team_employment));
        list.add(new MenuEntity("劳务发布",""+ R.drawable.icon_labour,R.drawable.icon_labour));
        list.add(new MenuEntity("工队发布",""+ R.drawable.icon_teams,R.drawable.icon_teams));
        return list;
    }

    /**
     * 企业工队发布数据
     * @return
     */
    public List<MenuEntity> getComList() {
        List<MenuEntity> list = new ArrayList<>();
        list.add(new MenuEntity("用工发布",""+ R.drawable.icon_team_employment,R.drawable.icon_team_employment));
        list.add(new MenuEntity("劳务发布",""+ R.drawable.icon_labour,R.drawable.icon_labour));
        list.add(new MenuEntity("工队发布",""+ R.drawable.icon_teams,R.drawable.icon_teams));
        return list;
    }
    //根据城市区域查询经纬度
    public void getLocation(Context context, String provinceName, String cityName) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int code) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int code) {
                if (code != 1000) {
                    return;
                }
                if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                        geocodeResult.getGeocodeAddressList().size() > 0) {
                    GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                    double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
                    double longitude = geocodeAddress.getLatLonPoint().getLongitude();//经度
                    //回调UI
                    ldLatLng.postValue(new LatLng(latitude, longitude));
                } else {
                    MToast.showToast(getApplication(), "地址名出错");
                }
            }
        });
        GeocodeQuery geocodeQuery = new GeocodeQuery(provinceName + cityName, cityName);
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }

    //根据经纬度查询城市区域
    public void getCityByLocation(Context context, double lat, double lon) {
        //通过经纬度获取位置信息
        GeocodeSearch geocodeSearch = new GeocodeSearch(context);
        // 第一个参数表示一个LatLng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat, lon), 200, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
        //搜索位置信息
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int code) {
                if (code != 1000) {
                    return;
                }
                RegeocodeAddress address = result.getRegeocodeAddress();
                if(TextUtils.isEmpty(address.getCity())){
                    MToast.showToast(context,"未获取到城市信息");
                    return;
                }
                //查找到市
                ldAddress.postValue(address);

            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int code) {

            }
        });
    }

    /**
     * 通过地址查找下标和省市区NO
     */
    public void findPositionByAddress(String provinceName, String cityName, String districtName) {
         Map<String,Object> mMap=new HashMap<>();
        //省市区弹窗选中位置
        int proPos = 0;
        //针对特殊省处理
        if (!TextUtils.isEmpty(provinceName)) {
            if (provinceName.contains("台湾")) {
                //针对特殊省处理
                provinceName = "台湾";
            } else if (provinceName.endsWith("市")) {
                //针对直辖市处理(适应接口)
                provinceName = provinceName.substring(0, provinceName.length() - 1);
            }
        }
        //查找省position
        for (AddressEntity entity : mProvinceList) {
            if (entity.getName().contains(provinceName)) {
                mMap.put("provinceNo",entity.getNo());
                proPos = mProvinceList.indexOf(entity);
                break;
            }
        }
        //查找市position
        List<AddressEntity> cityList;
        if (mCityList.size() > 0){
            cityList = mCityList.get(proPos);
            for (AddressEntity entity : cityList) {
                if (entity.getName().contains(cityName)) {
                    mMap.put("cityNo",entity.getNo());
                    break;
                }
            }
        }

        ldGetData.postValue(mMap);
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel(Context context,String provinceName,String cityName) {
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null) {
                    initAddress(context, data,provinceName,cityName);
                }
            }
        });
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private void initAddress(Context context, List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> list,String provinceName,String cityName) {
        //拷贝数据，保留原始数据
        String dataStr = GsonManager.getInstance().getGson().toJson(list);
        List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data = GsonManager.getInstance().getGson().fromJson(dataStr, new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType());
        //添加全国
        data.add(0, new AddressEntity("", "不限", "", "不限"));
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> pro : data) {
            //一级列表
            mProvinceList.add(pro);
            //二级列表
            if (pro.getChildren() == null) {
                pro.setChildren(new ArrayList<>());
            }
            //添加全省
            if (pro.getChildren().size() > 1) {
                pro.getChildren().add(0, new AddressEntity("", "不限", "", "不限"));
            }
            List<AddressEntity> cityList = new ArrayList<>(pro.getChildren());
            mCityList.add(cityList);
            //三级列表
            List<List<AddressEntity>> areaList = new ArrayList<>();
            for (AddressEntity<List<AddressEntity>> area : pro.getChildren()) {
                if (area.getChildren() == null) {
                    area.setChildren(new ArrayList<>());
                }
                area.getChildren().add(0, new AddressEntity("", "不限", "", "不限"));
                areaList.add(area.getChildren());
            }
            mDistrictList.add(areaList);
        }
        findPositionByAddress(provinceName, cityName, "");
    }
    //需求用工图查
    public void getEmploymentMap(Context context,Map<String,Object> map){
        DialogHelper.showProgressDialog(context,"加载中...").setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getEmploymentMap(map).enqueue(new ICallBack<BaseEntity<List<EmploymentEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<EmploymentEntity>> data) {
                       if(data.isSuccess()){
                           ldEmployment.postValue(data.getData());
                       }
            }
        });
    }
    //劳务用工图查
    public void getLabourMap(Context context,Map<String,Object> map){
        DialogHelper.showProgressDialog(context,"加载中...").setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getLabourMap(map).enqueue(new ICallBack<BaseEntity<List<LabourServiceAndEmploymentEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<LabourServiceAndEmploymentEntity>> data) {
                if(data.isSuccess()){
                    ldLabour.postValue(data.getData());
                }
            }
        });
    }
    //工程分包图查
    public void getProjectMap(Context context,Map<String,Object> map){
        DialogHelper.showProgressDialog(context,"加载中...").setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().projectSubcontractingMap(map).enqueue(new ICallBack<BaseEntity<List<TenderListEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<TenderListEntity>> data) {
                 if(data.isSuccess()){
                     ldTender.postValue(data.getData());
                 }
            }
        });

    }

    public void isDelEmployment(Context context,String no){
        DialogHelper.showProgressDialog(context,"加载中...").setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().isDeleteEmployment(no).enqueue(new ICallBack<BaseEntity<Boolean>>() {
            @Override
            public void onSuccess(BaseEntity<Boolean> data) {
                if(data.isSuccess()){
                    ldDelEmployment.postValue(data.getData());
                }
            }
        });
    }
    public void isDelDeleteLabor(Context context,String no){
        DialogHelper.showProgressDialog(context,"加载中...").setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().isDeleteLaborEmployment(no).enqueue(new ICallBack<BaseEntity<Boolean>>() {
            @Override
            public void onSuccess(BaseEntity<Boolean> data) {
                if(data.isSuccess()){
                    ldDelLabour.postValue(data.getData());
                }
            }
        });
    }

    public void follow(Context context,int type,boolean isAttention,String no) {
        DialogHelper.showProgressDialog(context, null, "", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().follow(isAttention,no,type).enqueue(new Callback<BaseEntity<String>>() {
            @Override
            public void onResponse(Call<BaseEntity<String>> call, Response<BaseEntity<String>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    ldFollow.postValue(isAttention);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<String>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void apply(Context context,Map<String,Object> map){
        DialogHelper.showProgressDialog(context, null, "", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPackerAPI().apply(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if(data.isSuccess()){
                    mSignUpSuccessLiveData.postValue(true);
                }
            }
        });
    }

    public void findCustomerServiceImAccount(Context context,String imId) {
        DialogHelper.showProgressDialog(context, null, "", 0, false, null).setCanceledOnTouchOutside(false);
        Map<String,Object> map = new HashMap<>();
        map.put("customerServiceContactsId", imId);
        APIManager.getInstance().getPickAPI().getfindCustomerServiceImAccount(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    MToast.showToast(context,response.body().getMsg());
                    mImLiveData.postValue(response.body().getMsg());
                } else {
                    // 接口返回的是String类型
                    String dataImId = response.body().getData().toString();
                    mImbLiveData.postValue(dataImId);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    public void getEmployment(Map<String,Object> map){
        mLoadGetData.postValue(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getEmploymentList(map).enqueue(new Callback<BaseEntity<ListResponse<List<EmploymentEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<EmploymentEntity>>>> call, Response<BaseEntity<ListResponse<List<EmploymentEntity>>>> response) {
                mSuccessGetData.postValue(true);
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    getEmploymentList.postValue(response.body().getData().getList());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<EmploymentEntity>>>> call, Throwable t) {
                mFailGetData.postValue(true);
            }
        });
    }

    public void getLabourList(Map<String,Object> map){
        mLoadGetData.postValue(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getLabourList(map).enqueue(new Callback<BaseEntity<ListResponse<List<LabourServiceAndEmploymentEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<LabourServiceAndEmploymentEntity>>>> call, Response<BaseEntity<ListResponse<List<LabourServiceAndEmploymentEntity>>>> response) {
                mSuccessGetData.postValue(true);
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    getLabourList.postValue(response.body().getData().getList());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<LabourServiceAndEmploymentEntity>>>> call, Throwable t) {
                mFailGetData.postValue(true);
            }
        });
    }

    public void getNewList(Map<String,Object> map) {
        mLoadGetData.postValue(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getTenderApplyingList(map).enqueue(new Callback<BaseEntity<List<TenderListEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<TenderListEntity>>> call, Response<BaseEntity<List<TenderListEntity>>> response) {
                mSuccessGetData.postValue(true);
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null) {
                        getTenderList.postValue(response.body().getData());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<TenderListEntity>>> call, Throwable t) {
                mFailGetData.postValue(true);
            }
        });
    }

    public void getLinkAgeWorkType(){
        mLoadGetData.postValue(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getLinkAgeWorkType().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                mSuccessGetData.postValue(true);
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<AddressEntity> list = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> datum : response.body().getData()) {
                        list.add(new AddressEntity("",datum.getName(),datum.getNo()));
                    }
                    list.add(0,new AddressEntity("","全部",""));
                    mSuccessWorkType.postValue(list);
                }else {
                    mFailGetData.postValue(true);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                mFailGetData.postValue(true);
            }
        });
    }

    public void getCategoryListTree(){
        mLoadGetData.postValue(true);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getFirstCategoryList().enqueue(new ICallBack<BaseEntity<List<PickFilterEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickFilterEntity>> data) {
                if(data.isSuccess()){
                    List<AddressEntity> list = new ArrayList<>();
                    for (PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>> datum : data.getData()) {
                        list.add(new AddressEntity("",datum.getName(),datum.getNo()));
                    }
                    list.add(0,new AddressEntity("","全部",""));
                    mSuccessWorkType.postValue(list);
                }else{
                    mFailGetData.postValue(true);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickFilterEntity>>> call, Throwable t) {
                mFailGetData.postValue(true);
            }
        });

    }
    public void editTender(Context mContext,String tenderNo, int isGz) {

         Map  map2 = new HashMap();
        map2.put("tenderNo", tenderNo);
        DialogHelper.showProgressDialog(mContext, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().editTender(map2).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mFocus.postValue(isGz);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getUrlSettingTender(String id) {
        APIManager.getInstance().getPickAPI().getUrlSetting("FrontDeskBidding").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id;
                    String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                    String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                    url = url + "&lng=" + lng + "&lat=" + lat;
                    mUrlTenderLiveData.postValue(url + "----" + id);
                }
            }
        });
    }
}
